// import { echarts } from '../../ec-canvas/echarts.js' //注意这样写是不管用的

import * as echarts from '../../ec-canvas/echarts';
const tabService = require("../../utils/tab-service");


var app = getApp();

// 自定义函数，格式化日期时间
function formatDate(date) {
    var year = date.getFullYear();
    var month = padZero(date.getMonth() + 1); //月份是从0开始的
    var day = padZero(date.getDate());
    return year + '-' + month + '-' + day;
}

function formatDate2(year, month, day) {
    var month = padZero(month + 1); //月份是从0开始的
    var day = padZero(day);
    return year + '-' + month + '-' + day;
}

// 自定义函数，补零
function padZero(num) {
    return (num < 10 ? '0' : '') + num;
}

function goTimeTrans(date) {
    var date = new Date(parseInt(date * 1000)); //如果date为13位不需要乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    return Y + M + D + h + m + s;
}
let processedBgs = []
// let avg_bg = "0.0"
// let percentage_ = "0"
// 将获得到的bg数据放到js的各项数据上
function sortBy(field) {
    //根据传过来的字段进行排序
    return (x, y) => {
        return x[field] - y[field]
    }
}

function bgsToJSData(bgs, predict = false) {
    if (predict)
        predictedData = [];
    else
        existedData = [];

    processedBgs = [];
    // var avgbg = 0;
    // var len = 0;
    // var currentDayStart = parseInt(new Date().getTime() / 1000);

    // 按时间排序
    if (bgs && bgs.length > 0) {
        bgs.sort(sortBy('time'));
        // bgs = bgs.filter(item => item.time <= currentTime);
    } else {
        console.log('bgs 是 null 或空数组');
    }

    // for (let i in bgs) {
    //     len += 1;
    //     var tmpbg = bgs[i];
    //     tmpbg.time = goTimeTrans(tmpbg.time);
    //     processedBgs.push(tmpbg);
    //     avgbg += bgs[i].value;
    // }
    // if (len == 0) {
    //     avgbg = 0;
    // } else {
    //     avgbg = avgbg / len;
    // }

    // // 保留一位小数
    // avg_bg = avgbg.toFixed(1).toString();
    // // 至此今日平均血糖值数据更新完毕
    // percentage_ = Math.round(avg_bg / 20 * 100);


    // 折线图数据更新完毕
    for (let i in bgs) {
        var tmpbg = bgs[i];
        tmpbg.time = goTimeTrans(tmpbg.time);
        processedBgs.push(tmpbg);
    }
    for (let i in processedBgs) {
        var tmpval = new Object();
        tmpval.value = [];
        tmpval.value.push(processedBgs[i].time);
        tmpval.value.push(processedBgs[i].value);
        if (predict)
            predictedData.push(tmpval);
        else
            existedData.push(tmpval);
    }

}

function jsTimeTrans(d) {
    return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
}


function time_label_formatter(value, index) {
    // console.log(value)
    // return "{HH}:{mm}";
    return "{H}点";
    // let remainder = index % 2;
    // if (index == 0) {
    //     remainder = 0;
    // }
    // if (remainder == 0) {
    //     return "{HH}:{mm}";
    // } else {
    //     return "";
    // }
}


function startToCurrentFilter(bgs) {

    // 获取当前时间的时间戳（以秒为单位）
    var currentTime = parseInt(new Date().getTime() / 1000);

    // var date=new Date();//测试后删除
    // date.setFullYear(fullYear,fullMonth,fullDay);//测试后删除
    // var currentTime = parseInt(date.getTime() / 1000);//测试后删除

    // // 获取今天零时的时间戳
    // var startOfDay = new Date(fullYear,fullMonth,fullDay);
    // var startOfDay = new Date();
    // startOfDay.setHours(0, 0, 0, 0);
    // var startOfDayTimestamp = parseInt(startOfDay.getTime() / 1000);

    // 按时间排序并过滤出当前时间以前的数据
    if (bgs && bgs.length > 0) {

        bgs = bgs.filter(item => item.time <= currentTime);
    } else {
        console.log('bgs 是 null 或空数组');
    }
    return bgs;
}

function currentToEndFilter(bgs) {
    console.log(bgs)

    // 获取当前时间的时间戳（以秒为单位）
    var currentTime = parseInt(new Date().getTime() / 1000);

    // 获取预测展示截止时间
    var endOfDay = new Date();
    // endOfDay.setHours(23, 59, 59, 999);
    endOfDay.setHours(endOfDay.getHours() + 2);
    var endOfDayTimestamp = parseInt(endOfDay.getTime() / 1000);

    console.log(currentTime);
    console.log(endOfDayTimestamp);
    // 按时间排序并过滤出当天的数据
    if (bgs && bgs.length > 0) {
        bgs = bgs.filter(item => {
            var itemTimestamp = item.time;
            return itemTimestamp > currentTime && itemTimestamp <= endOfDayTimestamp;
        });
    } else {
        console.log('bgs 是 null 或空数组');
    }
    console.log(bgs)
    return bgs;

}



function initChart(canvas, width, height, dpr) {
    chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
    });
    option.series[0].data = existedData;
    // option.series[1].data = predictedData;
    canvas.setChart(chart);
    chart.setOption(option, true);
    return chart;
}


let existedData = []
let predictedData = []
let chart;
let option = {
    grid: {
        containLabel: true,

    },
    tooltip: {
        show: true,
        //坐标轴触发
        //trigger:'cross',
        trigger: 'axis',
        //指示器线型
        axisPointer: {
            type: 'line',
            axis: 'x',
            snap: true
        }
    },

    dataZoom: [{
        type: 'inside',
        xAxisIndex: 0,
        start: 0, //数据窗口范围的起始百分比0-100
        end: 100, //数据窗口范围的结束百分比0-100
        filterMode: 'empty',
        zoomOnMouseWheel: true,
        moveOnMouseWheel: false
    }],
    xAxis: {
        type: 'time',
        boundaryGap: false, // 距离坐标原点是否有间隙
        min: '',
        max: '',
        interval: 3600,
        maxInterval: 4 * 60 * 60 * 1000,
        axisLabel: { //  如果这个字段不设置，echarts会根据屏宽及横坐标数据自动给出间隔
            // minInterval: 14400000, // 间隔长度，可自定义（如果是时间格式，echarts会自动处理） 不行感觉没用
            // maxInterval: 14400000,
            interval: 0,
            formatter: time_label_formatter,
            rotate: 0, // 横坐标上label的倾斜度
            showMinLabel: false,
            showMaxLabel: false,
            hideOverlap: false
        },
        axisLine: {
            show: true // 显示横轴线
        },
    },
    yAxis: {
        type: 'value',
        name: 'mmol/L',
        min: 0,
        max: 23,
        interval: 3,

        boundaryGap: false, // 距离坐标原点是否有间隙
        axisLabel: {
            formatter: '{value}',
            showMinLabel: false,
            showMaxLabel: false,
        },
        axisLine: {
            show: true, // 显示纵轴线
            // symbol:'arrow',
            lineStyle: {
                width: 1,
                type: [3, 5], //'dotted'
                dashOffset: 0,
            },
            symbol: ['none', 'arrow'],
            symbolSize: [5, 10]
        },
        axisPointer: {
            snap: true
        }
    },
    visualMap: { //区间内控制显示颜色
        show: false,
        type: 'piecewise', // 定义为分段型 visualMap
        // dimension: 0,//不要加dimension
        pieces: [{
                min: 10,
                color: '#ff6c6c'
            },
            {
                min: 3.9,
                max: 10,
                color: '#77e9ff'
            },
            {
                max: 3.9,
                color: '#00b26a'
            }
        ],
        // outOfRange: {
        //     color: '#ff4d4d'
        // }
    },

    series: [{
            name: "血糖值",
            type: 'line',
            smooth: true,
            // symbol: "none",
            showSymbol: true, //控制是否显示圆点
            // triggerLineEvent:false,
            data: existedData,
            lineStyle: {
                // 阴影部分
                width: 3, // 线条颜色、粗细
                // color: '#6dd4ee',
                shadowOffsetX: 0, // 折线的X偏移
                shadowOffsetY: 0, // 折线的Y偏移
                shadowBlur: 0, // 折线模糊
                // shadowColor: 'rgba(255, 181, 102, 0.4)' //折线颜色
            },
            // areaStyle: {
            //     color: {
            //         type: 'linear',
            //         // 线性渐变，前四个参数分别是 x0, y0, x2, y2, 范围从 0 - 1，相当于在图形包围盒中的百分比，如果 globalCoord 为 `true`，则该四个值是绝对的像素位置
            //         x: 0,
            //         y: 0,
            //         x2: 0,
            //         y2: 1,
            //         colorStops: [{
            //                 offset: 0,
            //                 color: 'rgba(18, 176, 207, 1)' // 0% 处的颜色
            //             },
            //             {
            //                 offset: 1,
            //                 color: 'rgba(18, 176, 207, 0)' // 100% 处的颜色
            //             }
            //         ],
            //         global: false // 缺省为 false
            //     },
            // },

        },
        // {
        //     name: "预测值",
        //     type: 'line',
        //     smooth: true,
        //     symbol: "none",
        //     data: predictedData,
        //     lineStyle: {
        //         // 阴影部分
        //         width: 3, // 线条颜色、粗细
        //         color: '#fad385',
        //         shadowOffsetX: 0, // 折线的X偏移
        //         shadowOffsetY: 0, // 折线的Y偏移
        //         shadowBlur: 0, // 折线模糊
        //         // shadowColor: 'rgba(255, 181, 102, 0.4)' //折线颜色
        //     },
        //     areaStyle: {
        //         color: {
        //             type: 'linear',
        //             x: 0,
        //             y: 0,
        //             x2: 0,
        //             y2: 1,
        //             colorStops: [{
        //                     offset: 0,
        //                     color: 'rgba(250, 211, 133, 1)' // 0% 处的颜色
        //                 },
        //                 {
        //                     offset: 1,
        //                     color: 'rgba(250, 211, 133, 0)' // 100% 处的颜色
        //                 }
        //             ],
        //             global: false // 缺省为 false
        //         },
        //     },

        // },
        {
            name: "markline",
            //标识线放在最后，否则遮挡渐变效果
            type: 'line',
            markLine: {
                symbol: ['none', 'none'], //['none']表示是一条横线；['arrow', 'none']表示线的左边是箭头，右边没右箭头；['none','arrow']表示线的左边没有箭头，右边有箭头
                label: {
                    position: "end" //将警示值放在哪个位置，三个值“start”,"middle","end" 开始 中点 结束
                },
                data: [{
                        name: "高值警戒",
                        silent: false, //鼠标悬停事件 true没有，false有
                        lineStyle: { //警戒线的样式 ，虚实 颜色
                            type: "solid", //样式  solid 和 dotted
                            color: "#6eba99",
                            width: 2 //宽度
                        },
                        yAxis: 3.9 // 警戒线的标注值，可以有多个yAxis,多条警示线 或者采用 {type : 'average', name: '平均值'}，type值有 max min average，分为最大，最小，平均值
                    },
                    {
                        name: "低值警戒",
                        silent: false, //鼠标悬停事件 true没有，false有
                        lineStyle: { //警戒线的样式 ，虚实 颜色
                            type: "solid", //样式  solid 和 dotted
                            color: "#6eba99",
                            width: 2 //宽度
                        },
                        yAxis: 10
                    }
                ]

            }
        },
    ]
}

Component({
    properties: {
        patient_id:0,
        showUploadBox: false,
        showPredictBox: false,
    },
    //页面数据
    data: {
        
        percentage: 0,
        existedData: '',
        predictedData: '',
        showPredictNote: false,
        showNoExistedNote: false,
        bloodSugarMin: 0,
        bloodSugarMax: 20,
        ec: {
            onInit: initChart
        },
        selectedTime: {
            minTime: '',
            maxTime: ''
        },
        // dateList: [],

        pickerVisible: false,
        years: [],
        months: [],
        days: [],
        currentDate: formatDate(new Date()),
        defaultDate: null,
        selectedCalendarDate: formatDate(new Date()),
        weekDay: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
        thisWeekDate: [],
        thisWeekSelectedIndex: -1,

        showCalendar: false,
        markCalendarList: []

    },
    methods: {
        onWeekDateClick(e) {
            var index = e.currentTarget.dataset.index;
            const {
                year,
                month,
                date
            } = this.data.thisWeekDate[index];
            var newDate = new Date(year, month, date);
            this.getThisWeek(newDate);
            this.setData({
                selectedCalendarDate: formatDate2(year, month, date)
            })
            console.log(this.data.selectedCalendarDate)

        },
        onShowCalendarChange(e) {
            this.setData({
                showCalendar: !this.data.showCalendar
            })
        },
        dateChange(e) {
            var year = e.detail.year;
            var month = e.detail.month;
            var date = e.detail.date;
            var newDate = new Date(year, month, date);
            newDate.setHours(0, 0, 0, 0);
            this.getThisWeek(newDate);
            this.setData({
                existedData: '',
                predictedData: '',
                showPredictNote: false,
            })
            this.showBloodSugarData(parseInt(new Date(year, month, date).getTime() / 1000));
            var today = new Date();
            today.setHours(0, 0, 0, 0);
            console.log(today.getTime())
            console.log(newDate.getTime())
            if (today.getTime() === newDate.getTime()) {
                console.log(1111)
                // 这里必须传当前时间，否则有错误
                this.getPredictedBloodSugarData(parseInt(new Date().getTime() / 1000));
            }
        },
        monthChange(e) {
            var year = e.detail.year;
            var month = e.detail.month;
            this.getDays(year, month);
        },
        yearChange(e) {
            var year = e.detail.year;
            this.getMonths(year)
        },

        onGoUploadClick(e) {
            wx.navigateTo({
                url: '../../pages/dataupload/dataupload',
            })
        },

        uploadByHandClick(e) {
            wx.navigateTo({
                url: '../../pages/bloodsugarrecord/bloodsugarrecord',
            })

        },
        uploadByFileClick(e) {
            wx.navigateTo({
                url: '../../pages/bloodsugarfile/bloodsugarfile',
            })
        },
        uploadByDeviceClick(e) {

        },



        /*****处理函数*****/
        getThisWeek(date) {
            var weekDate = []
            for (let i = 0; i < 7; i++) {
                var fullDate = {};
                var tempDate = new Date(date);
                tempDate.setDate(date.getDate() + i - 3);
                fullDate.year = tempDate.getFullYear();
                fullDate.month = tempDate.getMonth();
                fullDate.date = tempDate.getDate();
                fullDate.day = tempDate.getDay();
                weekDate.push(fullDate);
            }
            this.setData({
                thisWeekDate: weekDate,
                thisWeekSelectedIndex: 3
            })

        },
        getYears() {
            this.setData({
                years: [],
                months: [],
                days: []
            })
            wx.request({ // 调用接口
                url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/doctor?Action=GetBgFilter`,
                method: 'POST',
                header: {
                    "Content-Type": "application/json",
                    "x-api-key": wx.getStorageSync('token')
                },
                data: {
                    "patient_id": parseInt(this.data.patient_id),
                },
                success: (res) => {
                    console.log("getYears successfully",res);
                    if (res.statusCode == 200) {
                        var yearsList = res.data.message.filters;
                        this.setData({
                            years: yearsList
                        })
                    }
                }
            })
        },
        getMonths(year) {
            this.setData({
                months: [],
                days: []
            })
            wx.request({ // 调用接口
                url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/doctor?Action=GetBgFilter`,
                method: 'POST',
                header: {
                    "Content-Type": "application/json",
                    "x-api-key": wx.getStorageSync('token')
                },
                data: {
                    "patient_id": parseInt(this.data.patient_id),
                    "year": year,
                },
                success: (res) => {
                  console.log("getYears getMonths",res);
                    var monthsList = res.data.message.filters;
                    this.setData({
                        months: monthsList
                    })
                }
            })
        },
        getDays(year, month) {
            this.setData({
                days: []
            })
            const requestData = {
              "patient_id": parseInt(this.data.patient_id),
              "year": year,
              "month": month + 1
            }
            console.log("requestData in getYears",requestData)
            wx.request({ // 调用接口
                url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/doctor?Action=GetBgFilter`,
                method: 'POST',
                header: {
                    "Content-Type": "application/json",
                    "x-api-key": wx.getStorageSync('token')
                },
                data: requestData,
                success: (res) => {
                  console.log("getDays successfully",res);
                    var daysList = res.data.message.filters;
                    var spotsList = [];
                    if (daysList != null)
                        for (let day of daysList) {
                            spotsList.push(formatDate2(year, month, day));
                        }
                    this.setData({
                        days: daysList,
                        markCalendarList: spotsList
                    })
                }
            })
        },
        getBloodSugarData(time) {
            wx.request({ // 调用接口
                url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/doctor?Action=GetPatientBgs`,
                // url: 'https://124.220.110.138:443/bgmp/api/user?Action=ListBgs',
                method: 'POST',
                header: {
                    "Content-Type": "application/json",
                    "x-api-key": wx.getStorageSync('token')
                },
                data: {
                    "patient_id": parseInt(this.data.patient_id),
                    "start": time,
                    "end": time + 24 * 60 * 60 - 1
                },

                success: (res) => { // 接口调用成功，获取token并缓存
                  console.log("getBloodSugarData successfully",res);
                    if (res.statusCode == 200) {
                        var bgs = startToCurrentFilter(res.data.message.bgs);
                        console.log(bgs);

                        bgsToJSData(bgs);
                        this.setData({
                            // avg_sugar: avg_bg,
                            // percentage: percentage_,
                            existedData: existedData,
                            showNoExistedNote: existedData.length > 0 ? false : true

                        });
                        option.series[0].data = existedData;
                        console.log("获取血糖数据完成");
                        chart.setOption(option, true); // 得重新设置Option才会生效
                    } else {

                    }
                },
                fail() {
                    console.log("登录出现错误！");
                }
            })
        },
        showBloodSugarData(time) {
            var minTime = time * 1000;
            var maxTime = time * 1000 + 24 * 60 * 60 * 1000 - 1;
            this.setData({
                ['selectedTime.minTime']: minTime,
                ['selectedTime.maxTime']: maxTime,
            })
            option.xAxis.min = this.data.selectedTime.minTime;
            option.xAxis.max = this.data.selectedTime.maxTime;
            this.getBloodSugarData(time);
        },
        getPredictedBloodSugarData(time) {
            wx.request({ // 调用接口
                url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/algorithm?Action=BgPredict`,
                method: 'POST',
                header: {
                    "Content-Type": "application/json",
                    "x-api-key": wx.getStorageSync('token')
                },
                data: {
                    "time": time
                },
                success: (res) => { // 接口调用成功，获取token并缓存
                  console.log("getPredictedBloodSugarData successfully",res);
                    if (res.statusCode == 200) {
                        var results = res.data.message;
                        if (results.length > 0) {
                            results = results.filter(item => {
                                item.value = (item.value / 18).toFixed(1);
                                return res;
                            });
                        }
                        var todayResults = currentToEndFilter(results);
                        console.log(todayResults)
                        bgsToJSData(todayResults, true);

                        this.setData({
                            predictedData: predictedData,
                            showPredictNote: predictedData.length > 0 ? true : false,
                        });
                        // option.series[1].data = predictedData;
                        console.log("获取血糖预测数据完成");
                        // if (chart) {
                        //     chart.setOption(option, true); // 得重新设置Option才会生效
                        // }


                    } else {

                    }
                },
                fail() {
                    console.log("登录出现错误！");
                }
            })
        },
    },
    /**
     * 在组件实例进入页面节点树时执行
     */
    attached() {
        var today = new Date();
        today.setHours(0, 0, 0, 0); //改成十位日期形式
        this.setData({
            currentDate: formatDate(today)
        })

        this.showBloodSugarData(today.getTime() / 1000);
        if (this.data.existedData.length > 0)
            this.setData({
                showNoContentNote: false,
            });
        else
            this.setData({
                showNoContentNote: true,
            });
        this.getPredictedBloodSugarData(parseInt(new Date().getTime() / 1000));

        this.getYears();
        this.getThisWeek(today);

    },


})